#include "place.h"

void Place::partition(char *filename, int n, int m){
	
	const int MAX_LINE_LENGTH       = 65536;
  char line_buffer[MAX_LINE_LENGTH];
  
  char s_tmp[10];
  int x_tmp;
  int y_tmp;
  
  int max_x=0;
  int max_y=0;
  float step_x, step_y;	
	ifstream inp(filename);
  if (!inp.is_open()) {
      cerr << "Can't open input file:" <<filename<< endl;
      exit(1);
  }
  while(!inp.eof()){
  	inp.getline(line_buffer, MAX_LINE_LENGTH);
  	sscanf (line_buffer, "%s = %d %d", s_tmp, &x_tmp, &y_tmp);
  
  	
  	if(max_x < x_tmp)
  		max_x = x_tmp;
  		
  	if(max_y < y_tmp)
  		max_y = y_tmp;
  	
  	Signal *s=Ci->addSignal(s_tmp);
  	
  	s->x = x_tmp;
  	s->y = y_tmp;	
  }
  
  step_x = ((float)max_x)/n;
  step_y = ((float)max_y)/m;
  
  for(float i=0.0; i < max_x; i = i+step_x){
  	for(float j=0.0; j < max_y; j = j+step_y){
  		region r1;
  		r1.x0 = i;
  		r1.y0 = j;
  		r1.x1 = i+step_x;
  		r1.y1 = j+step_y;
  		regs.push_back(r1);
  	}
  }
  
  for(unsigned i=0; i<Ci->signalSize(); ++i){
  	if(	((Ci->getSignal(i)->x == 0) && (Ci->getSignal(i)->y == 0)) ||
  			(Ci->getSignal(i)->x<0) || (Ci->getSignal(i)->y<0)){
  		Ci->getSignal(i)->region = -1;
  		continue;
  	}
  	for(int j=0; j<regs.size(); ++j){
  		if( (Ci->getSignal(i)->x >= regs[j].x0) &&
  				(Ci->getSignal(i)->y >= regs[j].y0)	&&
  				(Ci->getSignal(i)->x < regs[j].x1)	&&
  				(Ci->getSignal(i)->y < regs[j].y1) )
  				
  				regs[j].signals.push_back(Ci->getSignal(i));
  				Ci->getSignal(i)->region = j;
  	}
  
  }
  for(int i=0; i<regs.size(); ++i)
  	for(int j=0; j<regs[i].signals.size(); ++j)
  		regs[i].signals[j]->region = i;
  for(int i=0; i<Ci->signalSize(); ++i){
  	if((Ci->getSignal(i)->region<0) || (Ci->getSignal(i)->region>regs.size()))
  	Ci->getSignal(i)->region = regs.size()/2;
  }
  
  int np1;
	bool test = true;
	while(test){
		np1=0;
		test = false;  
	  for(int i=0; i<Ci->gateSize(); ++i){
	  	if(Ci->getGate(i)->getOutput(0)->region == -1){
	//  		cout<<Ci->getGate(i)->getOutput(0)->getName()<<endl;
	  		++np1;
	  		test = true;
	  		for(int j=0; j<Ci->getGate(i)->inputSize(); ++j){
	  			if(Ci->getGate(i)->getInput(j)->region != -1 ){
	  				Ci->getGate(i)->getOutput(0)->region = Ci->getGate(i)->getInput(j)->region;
	  				break;
	  			}
	  		}
	  	}
	  }
	  for(int i=0; i<Ci->flipflopSize(); ++i){
	  	for(int k=0; k<Ci->getFlipflop(i)->outputSize(); ++k)
	  		Ci->getFlipflop(i)->getOutput(k)->region = Ci->getFlipflop(i)->getInput(1)->region;
	  }
	  //cout<<np1<<endl;
	}
  
}